<template>
  <div 
    class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4"
    v-if="visible"
    @click="handleOverlayClick"
  >
    <!-- 模态框容器 -->
    <div 
      class="bg-white rounded-lg shadow-xl w-full max-w-md mx-auto transform transition-all duration-300 scale-100"
      @click.stop
    >
      <!-- 模态框头部 -->
      <div class="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
        <h3 class="text-lg font-medium text-gray-900">新增用户</h3>
        <button 
          class="text-gray-400 hover:text-gray-500 focus:outline-none"
          @click="handleClose"
          aria-label="关闭"
        >
          <i class="fa fa-times"></i>
        </button>
      </div>
      
      <!-- 模态框内容 -->
      <div class="px-6 py-5">
        <form @submit.prevent="handleSubmit">
          <!-- 用户名 -->
          <div class="mb-4">
            <label for="name" class="block text-sm font-medium text-gray-700 mb-1">
              用户名 <span class="text-red-500">*</span>
            </label>
            <input
              id="name"
              v-model="formData.name"
              type="text"
              class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors"
              :class="errors.name ? 'border-red-500 focus:ring-red-500 focus:border-red-500' : ''"
              placeholder="请输入用户名"
            >
            <p v-if="errors.name" class="mt-1 text-sm text-red-600">{{ errors.name }}</p>
            <p class="mt-1 text-xs text-gray-500">
              3-20个字符，支持字母、数字和下划线
            </p>
          </div>
          
          <!-- 邮箱 -->
          <div class="mb-4">
            <label for="email" class="block text-sm font-medium text-gray-700 mb-1">
              邮箱 <span class="text-red-500">*</span>
            </label>
            <input
              id="email"
              v-model="formData.email"
              type="email"
              class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors"
              :class="errors.email ? 'border-red-500 focus:ring-red-500 focus:border-red-500' : ''"
              placeholder="请输入邮箱地址"
            >
            <p v-if="errors.email" class="mt-1 text-sm text-red-600">{{ errors.email }}</p>
            <p class="mt-1 text-xs text-gray-500">
              将用于用户登录和接收系统通知
            </p>
          </div>
          
          <!-- 角色 -->
          <div class="mb-4">
            <label for="roleId" class="block text-sm font-medium text-gray-700 mb-1">
              角色 <span class="text-red-500">*</span>
            </label>
            <select
              id="roleId"
              v-model="formData.roleId"
              class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors"
              :class="errors.roleId ? 'border-red-500 focus:ring-red-500 focus:border-red-500' : ''"
            >
              <option value="">请选择角色</option>
              <option 
                v-for="role in roles" 
                :key="role.id" 
                :value="role.id"
              >
                {{ role.name }}
              </option>
            </select>
            <p v-if="errors.roleId" class="mt-1 text-sm text-red-600">{{ errors.roleId }}</p>
          </div>
          
          <!-- 密码设置 -->
          <div class="mb-4">
            <div class="flex justify-between items-center mb-1">
              <label for="password" class="block text-sm font-medium text-gray-700">
                密码 <span class="text-red-500">*</span>
              </label>
              <button
                type="button"
                class="text-xs text-indigo-600 hover:text-indigo-800"
                @click="generatePassword"
              >
                生成密码
              </button>
            </div>
            <input
              id="password"
              v-model="formData.password"
              type="password"
              class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors"
              :class="errors.password ? 'border-red-500 focus:ring-red-500 focus:border-red-500' : ''"
              placeholder="请输入密码"
            >
            <p v-if="errors.password" class="mt-1 text-sm text-red-600">{{ errors.password }}</p>
            
            <!-- 密码强度指示器 -->
            <div v-if="formData.password" class="mt-2">
              <div class="flex justify-between text-xs mb-1">
                <span>密码强度</span>
                <span>{{ passwordStrengthText }}</span>
              </div>
              <div class="w-full bg-gray-200 rounded-full h-1.5">
                <div 
                  class="h-1.5 rounded-full transition-all duration-300"
                  :style="{ width: passwordStrength + '%' }"
                  :class="passwordStrengthClass"
                ></div>
              </div>
            </div>
            
            <p class="mt-1 text-xs text-gray-500">
              至少8个字符，包含字母和数字
            </p>
          </div>
          
          <!-- 全名 -->
          <div class="mb-4">
            <label for="fullName" class="block text-sm font-medium text-gray-700 mb-1">
              全名
            </label>
            <input
              id="fullName"
              v-model="formData.fullName"
              type="text"
              class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors"
              placeholder="请输入用户全名"
            >
          </div>
          
          <!-- 电话 -->
          <div class="mb-4">
            <label for="phone" class="block text-sm font-medium text-gray-700 mb-1">
              联系电话
            </label>
            <input
              id="phone"
              v-model="formData.phone"
              type="tel"
              class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors"
              placeholder="请输入联系电话"
            >
          </div>
          
          <!-- 发送欢迎邮件 -->
          <div class="mb-2">
            <label class="flex items-center">
              <input
                v-model="formData.sendWelcomeEmail"
                type="checkbox"
                class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded transition-colors"
                checked
              >
              <span class="ml-2 block text-sm text-gray-700">
                发送欢迎邮件（包含登录信息）
              </span>
            </label>
          </div>
        </form>
      </div>
      
      <!-- 模态框底部 -->
      <div class="px-6 py-4 bg-gray-50 rounded-b-lg flex justify-end space-x-3">
        <button
          type="button"
          class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors"
          @click="handleClose"
          :disabled="loading"
        >
          取消
        </button>
        <button
          type="button"
          class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors"
          @click="handleSubmit"
          :disabled="loading"
        >
          <i v-if="loading" class="fa fa-spinner fa-spin mr-1"></i>
          创建用户
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, watch, computed } from 'vue';
import { useValidator } from '@/composables/useValidator';

// 生成随机密码的工具函数
const generateRandomPassword = () => {
  const length = 10;
  const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%';
  let password = '';
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * charset.length);
    password += charset[randomIndex];
  }
  return password;
};

// 计算密码强度的函数
const calculatePasswordStrength = (password) => {
  if (!password) return 0;
  
  let strength = 0;
  
  // 长度检查
  if (password.length >= 8) strength += 25;
  if (password.length >= 12) strength += 10;
  
  // 包含小写字母
  if (/[a-z]/.test(password)) strength += 15;
  
  // 包含大写字母
  if (/[A-Z]/.test(password)) strength += 15;
  
  // 包含数字
  if (/[0-9]/.test(password)) strength += 15;
  
  // 包含特殊字符
  if (/[^A-Za-z0-9]/.test(password)) strength += 20;
  
  return strength;
};

export default {
  props: {
    // 控制模态框显示/隐藏
    visible: {
      type: Boolean,
      default: false
    },
    // 角色列表
    roles: {
      type: Array,
      default: () => []
    }
  },
  emits: ['close', 'save'],
  setup(props, { emit }) {
    // 表单数据
      const formData = ref({
        name: '',
        email: '',
        roleId: '',
        password: '',
        fullName: '',
        phone: '',
        sendWelcomeEmail: true,
        status: 'active' // 默认为激活状态
      });
    
    // 错误信息
    const errors = ref({});
    
    // 加载状态
    const loading = ref(false);
    
    // 验证器 composable
    const { validateEmail, validateRequired, validateUsername } = useValidator();
    
    // 监听visible变化，重置表单
      watch(() => props.visible, (newVisible) => {
        if (newVisible) {
          // 当模态框显示时重置表单
          formData.value = {
            name: '',
            email: '',
            roleId: '',
            password: '',
            fullName: '',
            phone: '',
            sendWelcomeEmail: true,
            status: 'active'
          };
          errors.value = {};
        }
      });
    
    // 密码强度计算
    const passwordStrength = computed(() => {
      return calculatePasswordStrength(formData.value.password);
    });
    
    // 密码强度文本描述
    const passwordStrengthText = computed(() => {
      const strength = passwordStrength.value;
      if (strength === 0) return '未设置';
      if (strength < 30) return '弱';
      if (strength < 60) return '中';
      return '强';
    });
    
    // 密码强度样式类
    const passwordStrengthClass = computed(() => {
      const strength = passwordStrength.value;
      if (strength === 0) return 'bg-gray-300';
      if (strength < 30) return 'bg-red-500';
      if (strength < 60) return 'bg-yellow-500';
      return 'bg-green-500';
    });
    
    // 生成随机密码
    const generatePassword = () => {
      formData.value.password = generateRandomPassword();
    };
    
    // 表单验证
    const validateForm = () => {
      const newErrors = {};
      
      // 验证用户名
      if (!validateRequired(formData.value.name)) {
        newErrors.name = '请输入用户名';
      } else if (!validateUsername(formData.value.name)) {
        newErrors.name = '用户名只能包含字母、数字和下划线';
      } else if (formData.value.name.length < 3 || formData.value.name.length > 20) {
        newErrors.name = '用户名长度必须在3-20个字符之间';
      }
      
      // 验证邮箱
      if (!validateRequired(formData.value.email)) {
        newErrors.email = '请输入邮箱地址';
      } else if (!validateEmail(formData.value.email)) {
        newErrors.email = '请输入有效的邮箱地址';
      }
      
      // 验证角色
      if (!validateRequired(formData.value.roleId)) {
        newErrors.roleId = '请选择角色';
      }
      
      // 验证密码
      if (!validateRequired(formData.value.password)) {
        newErrors.password = '请输入密码';
      } else if (formData.value.password.length < 8) {
        newErrors.password = '密码长度至少为8个字符';
      } else if (!/[a-zA-Z]/.test(formData.value.password) || !/[0-9]/.test(formData.value.password)) {
        newErrors.password = '密码必须包含字母和数字';
      }
      
      // 更新错误信息
      errors.value = newErrors;
      
      // 返回是否验证通过
      return Object.keys(newErrors).length === 0;
    };
    
    // 处理提交
    const handleSubmit = async () => {
      // 表单验证
      if (!validateForm()) {
        // 自动聚焦到第一个错误字段
        const firstErrorField = Object.keys(errors.value)[0];
        document.getElementById(firstErrorField)?.focus();
        return;
      }
      
      try {
        loading.value = true;
        // 触发保存事件，将表单数据传递给父组件
        emit('save', { ...formData.value });
      } catch (error) {
        console.error('提交表单失败:', error);
      } finally {
        loading.value = false;
      }
    };
    
    // 处理关闭
    const handleClose = () => {
      emit('close');
    };
    
    // 点击遮罩层关闭
    const handleOverlayClick = () => {
      handleClose();
    };
    
    return {
      formData,
      errors,
      loading,
      passwordStrength,
      passwordStrengthText,
      passwordStrengthClass,
      generatePassword,
      handleSubmit,
      handleClose,
      handleOverlayClick
    };
  }
};
</script>

<style scoped>
/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes scaleIn {
  from { transform: scale(0.95); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}

.fixed.inset-0 {
  animation: fadeIn 0.2s ease-out forwards;
}

.bg-white.rounded-lg {
  animation: scaleIn 0.2s ease-out forwards;
}
</style>
    